<template>
  <v-dialog v-model="isVisible" absolute max-width="400">
    <v-card data-testid="add-page-dialog-container">
      <v-card-title>{{ t('addPage.title') }}</v-card-title>
      <v-card-text>
        <v-text-field
          v-model="newUrl"
          :disabled="isLoading"
          :error="!!errorMessage"
          :error-messages="errorMessage"
          label="URL"
          :placeholder="t('addPage.urlPlaceholder')"
          @input="clearError"
          @keyup.enter="addUrl"
        />

        <!-- 边栏选择选项 -->
        <v-radio-group v-if="isMainWindow" v-model="selectedSidebar" class="mt-4">
          <v-radio
            data-testid="add-page-dialog-left-radio1"
            :label="t('addPage.addToLeft')"
            value="left"
          />
          <v-radio
            data-testid="add-page-dialog-right-radio1"
            :label="t('addPage.addToRight')"
            value="right"
          />
        </v-radio-group>

        <v-progress-linear v-if="isLoading" class="mt-2" color="primary" indeterminate />
        <div v-if="isLoading" class="text-caption text-center mt-2">
          {{ t('addPage.fetchingInfo') }}
        </div>
        <div v-if="missingSystemTabsForSelected.length > 0">
          <v-divider class="my-4" />
          <div class="text-subtitle-2 mb-2 d-flex align-center">
            <v-icon class="mr-1" :icon="mdiFlashOutline" size="18" />
            {{ t('addPage.quickAdd') }}
          </div>
          <div class="quick-add-grid">
            <v-card
              v-for="tab in missingSystemTabsForSelected"
              :key="tab.id"
              class="quick-add-card"
              variant="tonal"
              @click="addSystemTabQuick(tab, selectedSidebar === 'right')"
            >
              <v-card-item class="py-2">
                <v-avatar color="primary" size="24">
                  <v-icon :icon="tab.icon" size="18" />
                </v-avatar>
                <span class="text-caption ml-2 text-high-emphasis">{{ tab.title }}</span>
              </v-card-item>
            </v-card>
          </div>
        </div>
      </v-card-text>

      <v-card-actions>
        <v-btn
          data-testid="add-page-dialog-cancel-btn-1"
          :disabled="isLoading"
          text
          @click="closeDialog"
          >{{ t('addPage.cancel') }}</v-btn
        >
        <v-btn
          color="primary"
          data-testid="add-page-dialog-add-btn-1"
          :disabled="isLoading || !newUrl.trim()"
          :loading="isLoading"
          text
          @click="addUrl"
        >
          {{ t('addPage.add') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script lang="ts" setup>
import { formatUrl, isValidUrl } from '~shared/utils/urlUtils'
import {
  defaultLeftSystemTabs,
  defaultRightSystemTabs,
  useSidebarStore
} from '@/windows/layoutBrowser/stores/sidebar'

import { EscPriority, register } from '@/utils/esc-manager'
import { computed, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { mdiFlashOutline } from '@mdi/js'

const { t } = useI18n()
const isMainWindow = _pre_.browser.isMainWindow()

interface Props {
  /** 对话框是否可见 */
  visible: boolean
  /** 默认选择的边栏 */
  defaultSidebar?: 'left' | 'right'
}

interface Emits {
  (e: 'update:visible', value: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  defaultSidebar: 'left'
})

const emit = defineEmits<Emits>()

const sidebarStore = useSidebarStore()

const newUrl = ref('')
const isLoading = ref(false)
const errorMessage = ref('')
const selectedSidebar = ref<'left' | 'right'>(props.defaultSidebar)

// 快捷添加：计算左右侧未添加的系统默认标签
const leftExistingIds = computed(
  () => new Set(sidebarStore.leftTabs.map((s: F2.tab.Sidebar) => s.origin.id))
)
const rightExistingIds = computed(
  () => new Set(sidebarStore.rightTabs.map((s: F2.tab.Sidebar) => s.origin.id))
)

const leftMissingSystemTabs = computed(() =>
  defaultLeftSystemTabs.filter(t => !leftExistingIds.value.has(t.id))
)
const rightMissingSystemTabs = computed(() =>
  defaultRightSystemTabs.filter(t => !rightExistingIds.value.has(t.id))
)

const missingSystemTabsForSelected = computed(() =>
  selectedSidebar.value === 'right' ? rightMissingSystemTabs.value : leftMissingSystemTabs.value
)

function addSystemTabQuick(tab: F2.tab.Create, isRight: boolean) {
  sidebarStore.addSidebarTab(tab, isRight)
  closeDialog()
}

// 计算属性：对话框是否可见
const isVisible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

let unregisterEsc: undefined | (() => void)
watch(isVisible, v => {
  if (v) {
    unregisterEsc = register({
      id: 'modal-add-page',
      priority: EscPriority.MODAL,
      onEsc: () => {
        if (isVisible.value) {
          closeDialog()
          return true
        }
      }
    })
  } else {
    unregisterEsc?.()
    unregisterEsc = undefined
  }
})

onUnmounted(() => unregisterEsc?.())

// 监听默认边栏变化
watch(
  () => props.defaultSidebar,
  newValue => {
    selectedSidebar.value = newValue
  },
  { immediate: true }
)

/**
 * 添加新的URL到边栏标签页
 */
async function addUrl() {
  if (!newUrl.value.trim()) return

  // 清除之前的错误信息
  errorMessage.value = ''
  isLoading.value = true

  try {
    // 格式化URL
    const formattedUrl = formatUrl(newUrl.value.trim())

    // 验证URL格式
    if (!isValidUrl(formattedUrl)) {
      errorMessage.value = t('addPage.errors.invalidUrl')
      return
    }

    // 获取网站信息
    const { title, favicon, url } = await _pre_.siteInfo.fetchSiteInfo(formattedUrl)
    // 检查是否获取到有效数据
    if (!title || title.trim() === '') {
      errorMessage.value = t('addPage.errors.fetchFailed')
      return
    }

    // 根据选择的边栏创建标签页
    const tab = await sidebarStore.addSidebarTab(
      {
        url, // 使用重定向后的最终URL
        title,
        favicon
      },
      selectedSidebar.value === 'right'
    )

    // 成功后关闭弹窗并重置表单
    closeDialog()
    console.log(`成功添加${selectedSidebar.value === 'left' ? '左' : '右'}边栏标签:`, tab)
  } catch (error) {
    console.error('添加边栏标签失败:', error)
    errorMessage.value = t('addPage.errors.addFailed')
  } finally {
    isLoading.value = false
  }
}

/**
 * 关闭弹窗并重置状态
 */
function closeDialog() {
  isVisible.value = false
  newUrl.value = ''
  errorMessage.value = ''
  isLoading.value = false
}

/**
 * 清除错误信息
 */
function clearError() {
  errorMessage.value = ''
}
</script>

<style scoped>
.quick-add-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));
  gap: 6px;
}
.quick-add-card {
  cursor: pointer;
  transition:
    transform 0.18s ease,
    box-shadow 0.18s ease;
}
.quick-add-card:hover {
  transform: translateY(-1px);
}
</style>

<i18n>
{
  "zhHans": {
    "addPage": {
      "title": "添加边栏标签",
      "urlPlaceholder": "例如: https://www.example.com",
      "addToLeft": "添加到左侧边栏",
      "addToRight": "添加到右侧边栏",
      "fetchingInfo": "正在获取网站信息...",
      "quickAdd": "快捷添加",
      "cancel": "取消",
      "add": "添加",
      "errors": {
        "invalidUrl": "请输入有效的URL格式",
        "fetchFailed": "无法获取网站信息，请检查URL是否正确",
        "addFailed": "添加失败，请检查网络连接或URL是否正确"
      }
    }
  },
  "en": {
    "addPage": {
      "title": "Add Sidebar Tab",
      "urlPlaceholder": "e.g.: https://www.example.com",
      "addToLeft": "Add to Left Sidebar",
      "addToRight": "Add to Right Sidebar",
      "fetchingInfo": "Fetching site information...",
      "quickAdd": "Quick Add",
      "cancel": "Cancel",
      "add": "Add",
      "errors": {
        "invalidUrl": "Please enter a valid URL format",
        "fetchFailed": "Unable to fetch site information, please check the URL",
        "addFailed": "Failed to add, please check network connection or URL"
      }
    }
  }
}
</i18n>
